# Copyright (c) 2012 Nathan Grubb
# Available under the new BSD license; see LICENSE.txt

"""plugins/factoids.py: Implementation of IRC bot factoids, which are used to 
   store definitions by connecting them to phrases. They have the ability
   to be added, removed, or shown at any time.

   Command syntax is as follows (the factoids plugin uses a different prefix):
        add: !+phrase is definition
        delete: !-phrase
        show: !phrase
"""

import os
import shelve

class Factoids(object):
    commands = ("privmsg",)
    name = "Factoids"
    desc = "Plugin for bot factoids, based on the concept of the original infobot"
    type = "irc"
    permissions = None

    def __init__(self, api, msg):
        self.api = api
        self.msg = msg
        db_path = os.path.join(self.api.grubbot.plugin_dir, "factoids.db")
        self.db = shelve.open(db_path)

    def close(self):
        self.db.close()        

    def command_privmsg(self):
        line = " ".join(self.msg.args[1:])

        if line.startswith("!"):
            line = line.lstrip("!")

            if line.startswith("+"):
                line = line.lstrip("+")
                phrasedef = line.split(" is ", 1)

                if len(phrasedef) == 2:
                    phrase, definition = phrasedef
                    self.db[phrase] = definition
                    self.api.reply(self.msg, "Factoid added!")
                else:
                    self.api.reply(self.msg, "Syntax is: !+<phrase> is <definition>")

            elif line.startswith("-"):
                line = line.lstrip("-")
                if self.db.has_key(line):
                    del self.db[line]
                    self.api.reply(self.msg, "Factoid deleted!")
            else:
                if self.db.has_key(line):
                    self.api.reply(self.msg, self.db[line]) 

plugin = Factoids